<?php
require_once("constants.inc.php");

header("content-type: text/xml");

$oXmlManager = new XmlManager();

$oXmlContainer = $oXmlManager->openContainer(DBXML_CONTAINER);

if($_POST["p"])
{
  $sXml = str_replace(array("&gt;","&lt;","&amp;", "&quot;", "\\"), array(">","<","&","\"", ""), $_POST["p"]);

  $oXmlNewDoc = $oXmlManager->createDocument();
  $oXmlNewDoc->setContent($sXml);
  
  $oXmlContainer->putDocument($oXmlNewDoc, $oXmlManager->createUpdateContext(), DBXML_GEN_NAME);
}

if($_POST["u"])
{
  $sXml = str_replace(array("&gt;","&lt;","&amp;", "&quot;", "\\"), array(">","<","&","'", ""), $_POST["u"]);

  $sDBName = ereg_replace('.*dbxmlName\=[\'"](.*)["\']\ .*', "\\1", $sXml);
  $sXml = ereg_replace('(.*) ?dbxmlName\=[\'"](.*)[\'"](.*)', "\\1\\3", $sXml);

  $oXmlDoc = $oXmlContainer->getDocument($sDBName);

  $oXmlDoc->setContent($sXml);
  
  $context = $oXmlManager->createUpdateContext();
  $oXmlContainer->updateDocument($oXmlDoc, $context);
}

$oXmlDoc = $oXmlContainer->getAllDocuments();

/*  $oXmlDoc = $oXmlManager->query('
  let $con := collection("Blog.dbxml")
  let $c := $con
  return
	<result>
	  {
	  for $d in $c
	  return
		<d1 id="{$d}" />
	  }
	</result>
  ');
*/
$aRegExp = array(
  array("(\">)", '" dbxmlName="DBNAME\1'),
  array("(\/>)", 'dbxmlName="DBNAME" \1'),
  array("(><).*", " dbxmlName=\"DBNAME\" />\n"),
  array("([a-z])>(.*\/.*)", '\1 dbxmlName="DBNAME">\2')
);

echo "<return xmlns:dbxml=\"http://morglog.alleycatracing.com\">\n";

while($oXmlDoc->hasNext())
{
  $oNode = $oXmlDoc->next();
  $sName = $oNode->asDocument()->getName();

  if(!$oNode->asBoolean()) continue;
  
  $oDom = DOMDocument::loadXML($oNode->asString());
  $oElements = $oDom->getElementsByTagName("*");
  $sOut =  $oDom->saveHTML();

  foreach($aRegExp as $aReplace)
	$sOut = ereg_replace($aReplace[0], str_replace("DBNAME", $sName, $aReplace[1]), $sOut);

  echo $sOut;
}

echo '</return>';
?>
